package leja.notis;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class Main extends Activity implements FileSelectFragment.Callbacks, FileSaveFragment.Callbacks {
    // TO DO: include DEFAULT_DIR in settings
    private String DEFAULT_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    private String _readFile;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        ThemeChanger.onActivityCreateSetTheme(this);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id){
            case R.id.action_new:
                setNoteText("");
                return true;
            case R.id.action_open:
                ShowSelectDialog();
                return true;
            case R.id.action_save_as:
                ShowSaveAsDialog();
                return true;
            case R.id.action_settings:
                Intent intent=new Intent(this, SettingsActivity.class);
                startActivity(intent);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void ShowSelectDialog() {
        String fragTag = getResources().getString(R.string.tag_fragment_FileSelect);

        // Set up a selector for file selection rather than directory selection.
        FileSelectFragment fsf = FileSelectFragment.newInstance(FileSelectFragment.Mode.FileSelector,
                R.string.alert_ok,
                R.string.alert_cancel,
                R.string.alert_file_select,
                R.drawable.ic_launcher,
                R.drawable.ic_launcher, // TO DO: add icon for directories
                R.drawable.ic_launcher);// TO DO: add icon for files

        // Restrict selection to *.txt files
        ArrayList<String> allowedExtensions = new ArrayList<String>();
        allowedExtensions.add(".txt");
        fsf.setFilter(FileSelectFragment.FiletypeFilter(allowedExtensions));

        fsf.show(getFragmentManager(), fragTag);
    }

    @Override
    public boolean isValid(String absolutePath, String fileName) {
        // check if the selected file is valid for opening, return false if it isn't
        if ((_readFile = ReadFile(absolutePath + "/" + fileName)) == null) {
            Toast.makeText(this, R.string.alert_invalid_file, Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    @Override
    public void onConfirmSelect(String absolutePath, String fileName) {
        if (absolutePath == null || fileName == null) {
            return;
        }

        setNoteText(_readFile);
    }

    public void ShowSaveAsDialog() {
        String xml = getResources().getString(R.string.file_extension_xml);
        String fragTag = getResources().getString(R.string.tag_fragment_FileSave);

        // Get an instance supplying a default extension, captions and
        // icon appropriate to the calling application/activity.
        FileSaveFragment fsf = FileSaveFragment.newInstance(xml,
                R.string.alert_ok,
                R.string.alert_cancel,
                R.string.alert_file_save_as,
                R.string.hint_filename_unadorned,
                R.drawable.ic_launcher);

        fsf.show(getFragmentManager(), fragTag);
    }

    @Override
    public boolean onCanSave(String absolutePath, String fileName) {
        if (fileName.length() == 0) {
            Toast.makeText(this, R.string.alert_no_filename, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    public void onConfirmSave(String absolutePath, String fileName) {
        if (absolutePath == null || fileName == null) {
            return;
        }

        EditText editText = (EditText) findViewById(R.id.input_text);
        String text = editText.getText().toString();

        SaveFile(text, absolutePath + "/" + fileName);
    }

    public String getNoteText() {
        EditText editText = (EditText) findViewById(R.id.input_text);
        String text = editText.getText().toString();

        return text;
    }

    public void setNoteText(String text) {
        EditText editText = (EditText) findViewById(R.id.input_text);
        editText.setText(text);
    }

    public String getNewFileName() {
        // TO DO: implement filename generator
        return "note.txt";
    }

    public void SaveFile(String text, String path) {
        // TO DO: get rid of try catch
        try {
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            osw.append(text);
            osw.close();
            fOut.close();

            Toast.makeText(getBaseContext(),
                    R.string.save_success,
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    public String ReadFile(String path) {
        File file = new File(path);

        StringBuilder text = new StringBuilder();

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
        }
        catch (IOException e) {
            return null;
        }

        return text.toString();
    }

    public void btnSaveClicked(View view) {
        SaveFile(getNoteText(), DEFAULT_DIR + getNewFileName());
    }

}
